import System from './System'
import HttpBean, { type Res } from './HttpBean'
export default class HttpUtil {
    static url = 'https://zj.v.api.aa1.cn'

    static http: HttpBean = null as any

    static post<T = any>(optoins: any, data: any = {}): Promise<Res<T>> {
        if (this.http == null) this.init()
        return this.http.post(optoins, data)
    }

    static get<T = any>(optoins: any, data: any = {}): Promise<Res<T>> {
        if (this.http == null) this.init()
        return this.http.get(optoins, data)
    }

    static async init() {
        /**
         * 请求前处理
         * @param config
         */
        const req = (headerObj: any) => {
            headerObj['Authorization'] = 'Bearer '
        }

        /**
         * 请求后处理
         * @param res
         * @returns
         */
        const res = (res: any, optoins: any) => {
            if (res.status) {
                if (res.message && optoins.message) System.sr(res.message)
                return res
            } else {
                if (res.message && optoins.message) System.er(res.message)
                switch (res.code) {
                    case '401':
                        System.er('无效的权限信息')
                        return res
                    default:
                        break
                }
            }
            return res
        }

        const error = (e: any) => {
            const err = e.statusCode + ''
            let errorCtxTemp: any = null
            if (err === '501') errorCtxTemp = '请求超时'
            else if (err === '404') errorCtxTemp = '不存在该接口'
            else if (err === '401') errorCtxTemp = '无操作权限'
            else errorCtxTemp = '网络异常'
            System.er(errorCtxTemp)
        }

        this.http = new HttpBean({
            baseUrl: HttpUtil.url,
            req,
            res,
            error
        })
    }
}
